/**
 * @Author: easten
 * @Created: 2024-04-15 23:48:14
 * @Description:
 *
 */
import { ApiDevice, ApiDeviceGroup } from "_common/api/iot";
import { DrawerProps, TreeDataModel } from "_common/DataType";
import { IotDevice, IotDeviceGroup } from "_common/entity";
import { AxiosInstance } from "axios";
import React, { useState, useEffect, useMemo, useRef } from "react";
import {
  Button,
  Drawer,
  Form,
  FormInstanceFunctions,
  Input,
  InputNumber,
  MessagePlugin,
  Switch,
} from "tdesign-react";
import FormItem from "tdesign-react/es/form/FormItem";
type DeviceDrawerProps = DrawerProps & {
  terminal?: TreeDataModel;
  groupCode?: number;
  axios: AxiosInstance;
};
const DeviceDrawer: React.FC<DeviceDrawerProps> = (
  props: DeviceDrawerProps
) => {
  const { open, axios, edit, onSuccess, value, terminal, copy, groupCode } =
    props;
  const formRef = useRef<FormInstanceFunctions>();

  // 设备分组信息
  const [deviceGroup, setDeviceGroup] = useState<IotDeviceGroup[]>([]);

  const apiDevice = new ApiDevice(axios);
  const apiDeviceGroup = new ApiDeviceGroup(axios);

  // 监听选中的设备分组
  const [form] = Form.useForm();
  // const groupCode = Form.useWatch("dtCode", form);

  useEffect(() => {
    return () => {
      formRef.current?.reset();
    };
  }, []);

  useEffect(() => {
    getDeviceGroup();
    if (value && edit) {
      // 解构value
      let data = {
        ...value,
      };
      formRef.current?.setFieldsValue(data);
      const _time = setTimeout(() => {
        formRef.current?.setFieldsValue(value?.deviceAttr);
        clearTimeout(_time);
      }, 100);
    }
  }, [edit, value]);

  // 复制
  useEffect(() => {
    if (value && copy) {
      formRef.current?.setFieldsValue({
        ...value,
        deviceName: `${value.deviceName}-copy`,
        deviceCode: `${value.deviceCode + 1}`,
        orderNo: value.orderNo + 1,
      });
      setTimeout(() => {
        formRef.current?.setFieldsValue(value?.deviceAttr);
      }, 100);
    }
    return () => {};
  }, [copy, value]);

  const handleClose = () => {
    onSuccess?.(false);
    formRef.current?.reset();
  };

  // 动态表单
  const dynamicFormItem = useMemo(() => {
    if (!groupCode) return null;
    let group = deviceGroup.find((item) => item.groupCode == groupCode);
    if (!group?.rltAttrs) return null;
    return group?.rltAttrs.map((item) => {
      return (
        <FormItem
          key={item.id}
          label={item.attrName}
          rules={[{ required: true }]}
          name={item.attrCode}
        >
          {item.dataType == "string" && <Input />}
          {item.dataType == "integer" && <InputNumber />}
          {item.dataType == "float" && <InputNumber />}
          {item.dataType == "boolean" && <Switch label={["是", "否"]} />}
        </FormItem>
      );
    });
  }, [groupCode, deviceGroup]);

  // 获取设备分组信息
  const getDeviceGroup = async () => {
    const response = await apiDeviceGroup.getDeviceGroupList();
    if (response && response.code == 200 && response.data) {
      setDeviceGroup(response.data);
    }
  };

  // 新增设备
  const createDevice = async (data: IotDevice) => {
    // 解构动态表单数据
    let { dtCode, deviceCode, deviceName, orderNo, ...deviceAttr } = data;
    const response = await apiDevice.createDevice({
      terminalId: terminal?.value,
      dtCode: groupCode,
      deviceCode,
      deviceName,
      deviceAttr,
      orderNo,
    });
    if (response && response.code == 200 && response.data) {
      MessagePlugin.success("新增成功");
      handleClose();
    }
  };
  // 更新设备
  const updateDevice = async (data: IotDevice) => {
    let { dtCode, deviceCode, deviceName, orderNo, ...deviceAttr } = data;
    const response = await apiDevice.updateDevice({
      terminalId: terminal?.value,
      dtCode: groupCode,
      deviceCode,
      deviceName,
      deviceAttr,
      orderNo,
      id: value?.id,
    });
    if (response && response.code == 200 && response.data) {
      MessagePlugin.success("更新成功");
      handleClose();
    }
  };

  return (
    <Drawer
      header={`${edit ? "编辑" : "添加"}设备`}
      footer={false}
      visible={open}
      sizeDraggable
      size="medium"
      onClose={handleClose}
    >
      <Form
        form={form}
        ref={formRef}
        labelWidth={100}
        onSubmit={async (data) => {
          // 是否校验通过
          if ((await formRef.current?.validateOnly()) == true) {
            edit
              ? updateDevice(data.fields as IotDevice)
              : createDevice(data.fields as IotDevice);
          }
        }}
      >
        {/*  <FormItem label="选择产品" rules={[{ required: true }]} name="dtCode">
          <Select
            options={deviceGroup?.map((item) => {
              return { label: item.groupName, value: item.groupCode };
            })}
          />
        </FormItem> */}
        <div className="m-5">
          设备类型
          <span className="ml-8">
            {
              deviceGroup?.find((item) => item.groupCode == groupCode)
                ?.groupName
            }
          </span>
        </div>
        <FormItem
          label="设备名称"
          rules={[{ required: true }]}
          name="deviceName"
        >
          <Input />
        </FormItem>
        <FormItem label="设备ID" rules={[{ required: true }]} name="deviceCode">
          <Input />
        </FormItem>
        <FormItem label="设备序号" rules={[{ required: true }]} name="orderNo">
          <InputNumber />
        </FormItem>
        {dynamicFormItem}
        <FormItem className="float-right">
          <Button type="submit" theme="primary">
            提交
          </Button>
          <Button type="reset" theme="success" style={{ marginLeft: 12 }}>
            重置
          </Button>
        </FormItem>
      </Form>
    </Drawer>
  );
};
export default DeviceDrawer;
